package com.lcb.rabbitmq.task;

import com.lcb.rabbitmq.entity.MsgLog;
import com.lcb.rabbitmq.mapper.MsgLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;


@Component
@Slf4j
public class ResendMsg {

    @Autowired
    private MsgLogMapper msgLogMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 最大投递次数
    private static final int MAX_TRY_COUNT = 3;

    @Scheduled(cron = "0/30 * * * * ?")
    public void resned() {
        log.info("开始执行定时任务(重新投递消息)");
        Example example = new Example(MsgLog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", 0);
        criteria.orLessThanOrEqualTo("nextTryTime", new Date());
        List<MsgLog> msgLogs = msgLogMapper.selectByExample(example);

        msgLogs.forEach(msgLog -> {

            String msgId = msgLog.getMsgId();
            if (msgLog.getTryCount() >= MAX_TRY_COUNT) {
                msgLog.setStatus(2);
                msgLogMapper.updateByPrimaryKeySelective(msgLog);
                log.info("超过最大重试次数, 消息投递失败, msgId: {}", msgId);
            } else {
                msgLog.setTryCount(msgLog.getTryCount() + 1);
                msgLogMapper.updateByPrimaryKeySelective(msgLog);
                CorrelationData correlationData = new CorrelationData();
                correlationData.setId(msgId);
                rabbitTemplate.convertAndSend(msgLog.getExchange(), msgLog.getRoutingKey(), msgLog.getMsg(), correlationData);
                log.info("第 " + (msgLog.getTryCount() + 1) + " 次重新投递消息");
            }
        });

        log.info("定时任务执行结束(重新投递消息)");
    }
}
